import { Navigate, useLocation } from "react-router-dom";
import { User, UserRole, RouteElement  } from '../routes/type';
import {ReactElement} from "react"
 
interface AuthGuardProps{
  element: RouteElement,
  requiresAuth: boolean;
  roles?: UserRole[]
}
 
const AuthGuard = ({ element, requiresAuth, roles }: AuthGuardProps): ReactElement | null => {
  const userStr = localStorage.getItem("user");
  const currentUser = userStr ? JSON.parse(userStr) : null;
  const location = useLocation();
 
  if (requiresAuth && !currentUser) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }
 
  if (
    requiresAuth &&
    roles &&
    roles.length > 0 &&
    !roles.includes(currentUser?.role)
  ) {
    return <Navigate to="/" replace />;
  }
 
  return <>{element}</>;
};
 
export default AuthGuard;